package com.awa.usercenter.service.impl;

import com.awa.usercenter.common.Code;
import com.awa.usercenter.common.utils.JwtUtils;
import com.awa.usercenter.exception.BusinessException;
import com.awa.usercenter.mapper.UserMapper;
import com.awa.usercenter.model.code.SmsAuthenticationToken;
import com.awa.usercenter.model.domain.User;
import com.awa.usercenter.service.CodeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
* @author zhengcan
*/

@Service
@Slf4j
public class CodeUserServiceImpl extends ServiceImpl<UserMapper, User> implements CodeService {

    @Autowired
    private JwtUtils jwtUtils;
    private final AuthenticationManager authenticationManager;

    public CodeUserServiceImpl(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }
    @Override
    public String userCodeLoginToken(String phone, String smsCode) {
        // todo
        if(StringUtils.isAnyBlank(phone, smsCode)){
            throw new BusinessException(Code.NULL_ERROR);
        }
        // 账户不包含特殊字符
        String validPattern = "\\w{6,}";
        Matcher matcher = Pattern.compile(validPattern).matcher(phone);
        if(!matcher.find()){
            return null;
        }
        SmsAuthenticationToken authentication = new SmsAuthenticationToken(phone,smsCode);
        System.out.println(authentication);
        Authentication authenticate = null;
        try{
            authenticate = authenticationManager.authenticate(authentication);
            SecurityContextHolder.getContext().setAuthentication(authenticate);
        }catch(BadCredentialsException e)
        {
            log.error("用户名或密码错误");
            throw new BusinessException(Code.PARAMS_ERROR, "用户名或密码错误");
        }
        System.out.println(authenticate.getPrincipal());
        User principal = (User) authenticate.getPrincipal();
        HashMap<String,Object> map = new HashMap<>();
        map.put("userId",principal.getUserId());
        map.put("phone",principal.getPhone());
        map.put("roles",principal.getRoleSet());
        return jwtUtils.createToken(map);
    }

}




